<template>
  <div class="course-list">
    <div class="filter-container">
      <h2>课程解析</h2>
      <el-button
        type="primary"
        icon="CirclePlus"
        @click="handleAdd(submitForm)"
        :loading="loading"
      >
        新增记录
      </el-button>
    </div>
    <el-table
      class="header-lighter"
      :data="tableData"
      stripe
      highlight-current-row
      show-overflow-tooltip
      fit
      v-loading="loading"
      height="calc(100vh - 140px)"
    >
      <el-table-column label="名称" min-width="200" prop="course_name" />
      <el-table-column label="文件时长" min-width="200" prop="">
        <template #default="scope">
          {{ formatTime(scope.row.duration) }}
        </template>
      </el-table-column>
      <el-table-column
        label="音频解析状态"
        align="center"
        min-width="200"
        prop="create_at"
      >
        <template #default="scope">
          <!-- <el-tag type="primary" v-if="scope.row.status == enumCourse.inLine">{{
            courseEnumMapText[enumCourse.inLine]
          }}</el-tag> -->
          <el-tag type="success" v-if="scope.row.status == enumCourse.SUCCESS">
            {{ courseEnumMapText[enumCourse.SUCCESS] }}
          </el-tag>
          <el-tag type="warning" v-if="scope.row.status == enumCourse.PEDDING"
            >{{ courseEnumMapText[enumCourse.PEDDING] }}
          </el-tag>
          <el-tag type="danger" v-if="scope.row.status == enumCourse.FAIL">
            {{ courseEnumMapText[enumCourse.FAIL] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column width="100" fixed="right" label="操作">
        <template #default="scope">
          <el-space>
            <el-icon
              v-if="scope.row.status == enumCourse.SUCCESS"
              style="color: var(--el-color-primary); cursor: pointer"
              @click="handleTranscripts(scope.row)"
              size="20"
            >
              <Search />
            </el-icon>
            <span v-else> -- </span>
            <el-icon
                style="color: var(--el-color-danger); cursor: pointer"
                @click="handleDelete(scope.row.id)"
                size="20"
              >
                <Delete />
            </el-icon>
          </el-space>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="dataTotal"
      v-model:limit="query.limit"
      v-model:page="query.page"
      @pagination="getTableData"
    />

    <el-dialog
      v-model="dialogVisible"
      title="音视频速读"
      @close="handleClose"
      width="800px"
    >
      <div
        :style="{
          display: videoURL || uploadFileLoading ? 'flex' : '',
          alignItems: 'center',
          justifyContent: 'center',
          width: '100%',
          gap: '20px',
        }"
      >
        <el-upload
          drag
          accept=".mp4,.wmv,.m4v,.flv,.rmvb,.dat,.mov,.mkv,.webm,.avo,.mpeg,.3gp,.ogg"
          :before-upload="beforeUpload"
          :on-success="successAction"
          :on-progress="handleProgress"
          :on-change="handleChange"
          v-model:file-list="fileList"
          :show-file-list="false"
          style="min-width: 400px"
          :action="actionURL"
          name="files"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            <em>点击或将音视频文件拖拽到此处上传 </em>
          </div>
        </el-upload>
        <div
          :style="{
            border: videoURL ? '1px solid #ccc' : '',
            padding: '10px',
            borderRadius: '5px',
          }"
        >
          <video
            v-if="videoURL"
            style="width: 100%; height: 100%"
            :src="videoURL"
            controls
          ></video>
          <div style="width: 100%" v-if="uploadFileLoading">
            <el-skeleton style="width: 240px" :loading="true" animated>
            </el-skeleton>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleConfirm"
            :loading="uploadFileLoading"
            :disabled="!videoURL"
          >
            {{ uploadFileLoading ? '上传中' : '确认' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from 'vue'
import { enumCourse, courseEnumMapText } from '@/enum'
import { httpGetCourseList, httpCreateCourseAnalysis, httpDeleteCourseAnalysis } from '@/api/course.js'
import { ElMessageBox, ElMessage } from 'element-plus'
import Pagination from '@/components/pagination/index.vue'
import { useRouter } from 'vue-router'
import { Message, UploadFilled } from '@element-plus/icons-vue'
import { deleteFile } from '@/api/file.js'

const actionURL = import.meta.env.VITE_BASE_API + '/upload/files'
const router = useRouter()
const tableData = ref([{ avatar: '' }])
const dataTotal = ref(0)
const dialogVisible = ref(false)
const fileList = ref([])
const videoIds = ref([])
const videoURL = ref('')
const fileName = ref('未知文件名')
const uploadFileLoading = ref(false)
const confirmLoading = ref(false)
const query = reactive({
  page: 1,
  limit: 20,
  keyword: '',
})
const loading = ref(false)
const submitForm = ref()

const handleProgress = (response) => {
  videoURL.value = ''
  uploadFileLoading.value = true
}
const handleChange = (files) => {
  fileName.value = files?.name?.split('.')[0] || '未知文件名'
}
const successAction = async (response) => {
  if (response.code !== 200) {
    ElMessage.error(response.message)
    return
  }
  uploadFileLoading.value = false
  if (videoIds.value.length) {
    videoURL.value = ''
    await deleteFile(videoIds.value[0])
  }
  const d = response.data.list[0]
  videoIds.value = [d.file_id]
  videoURL.value = import.meta.env.VITE_BASE_API + '/storage/' + d.file_id
}

const getTableData = async () => {
  loading.value = true
  const response = await httpGetCourseList({
    ...query,
  })
    .catch(() => null)
    .finally(() => {
      loading.value = false
    })

  if (!response) {
    return
  }
  tableData.value = response.list
  dataTotal.value = response.total
}
const handleSeach = () => {
  query.page = 1
  getTableData()
}
// 新增记录
const handleAdd = async (formEl) => {
  dialogVisible.value = true
}
const handleTranscripts = (row) => {
  if (row.status === enumCourse.SUCCESS) {
    router.push('/course/transcripts/' + row.id)
  }
}

onMounted(() => {
  getTableData()
})

const handleClose = () => {
  fileList.value = []
  videoURL.value = ''
  videoIds.value = []
  uploadFileLoading.value = false
}
const formatTime = (duration) => {
  const hours = Math.floor(duration / 3600)
  const minutes = Math.floor((duration % 3600) / 60)
  const seconds = Math.floor(duration % 60)
  return `${hours ? hours + '小时' : ''}${minutes}分钟${seconds}秒`
}
const beforeUpload = (file, max_size = 30000) => {
  let type_arr = ['video']
  let type = file.type.split('/')[0]
  if (!type_arr.includes(type)) {
    ElMessage.error('视频格式不正确,只支持video类型')
    return false
  }
  if (file.size > 1024 * 1024 * max_size) {
    ElMessage.error(`视频大小请不要超过${max_size}M`)
    return false
  }
}

const handleConfirm = async () => {
  try {
    confirmLoading.value = true
    const res = await httpCreateCourseAnalysis({
      file_name: fileName.value,
      file_id: videoIds.value[0],
    })
    if (res) {
      dialogVisible.value = false
      ElMessage.success('创建成功')
      handleSeach()
    }
  } catch (error) {
    console.error(error)
  } finally {
    confirmLoading.value = false
  }
}
const handleDelete = async (id) => {
  console.log(typeof id)
  const confirm = await ElMessageBox.confirm('确认删除此项？')
    .then(() => true)
    .catch(() => false)
  if (!confirm) return
  loading.value = true
  const response = await httpDeleteCourseAnalysis({ course_id: id })
    .then(() => true)
    .catch(() => false)
  if (response) {
    await getTableData()
  } else {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.course-list {
  height: 100%;
}
.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-lighter {
  height: calc(100% - 60px);
}
</style>
